package com.crazyktv.wcf.android;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.crazyktv.wcf.android.Util.DoAction;

@SuppressLint("NewApi")
public class WaitList extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		myVibrator = (Vibrator) getApplication().getSystemService(
				Service.VIBRATOR_SERVICE);
	}

	@Override
	protected void onResume() {
		super.onResume();
		getSongList();
		//handler.postDelayed(runnable, Util.prefRefresh);
		handler.postDelayed(runnable, Util.prefRefreshTime);
	}

	@Override
	protected void onPause() {
		super.onPause();
		handler.removeCallbacks(runnable);
	}

	private Handler handler = new Handler();

	private Runnable runnable = new Runnable() {
		public void run() {
			getSongList();
			handler.postDelayed(this, Util.prefRefreshTime);
		}
	};

	protected static Vibrator myVibrator = null;
	private LinearLayout layoutMain;
	private ListView lv;

	private void getSongList() {
		Log.d("refresh",String.valueOf(new Date().toString()));
		layoutMain = SongQuery.linearLayout(1, this);

		String s = Util.ViewSong();
		if (!s.equals("[]")) {
			// get list
			lv = listView();
			ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
			try {
				JSONArray jsonArray = new JSONArray(s);
				Log.d("json", String.valueOf(jsonArray.length()));
				for (int i = 0; i < jsonArray.length(); i++) {
					HashMap<String, String> map = new HashMap<String, String>();
					JSONObject e = jsonArray.getJSONObject(i);
					map.put("id", e.getString("Song_Id"));
					map.put("stroke", "");
					// map.put("stroke", e.getString("stroke") + " 劃");
					map.put("singer", e.getString("Song_Singer"));
					map.put("title", e.getString("Song_SongName"));
					map.put("type", e.getString("Song_Lang"));
					mylist.add(map);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			// readJSON

			ListAdapter adapter = new SimpleAdapter(this, mylist,
					R.layout.list2, new String[] { "id", "stroke", "singer",
							"title", "type" }, new int[] { R.id.text1,
							R.id.text2, R.id.text3, R.id.text4, R.id.text5 });
			lv.setAdapter(adapter);
			registerForContextMenu(lv);
			lv.setOnItemClickListener(new OnItemClickListener() {
				public void onItemClick(AdapterView<?> a, View v, int position,
						long id) {
					TextView tvId = (TextView) v.findViewById(R.id.text1);
					TextView tvSinger = (TextView) v.findViewById(R.id.text3);
					TextView tvTitle = (TextView) v.findViewById(R.id.text4);
					String singer = tvSinger.getText().toString();
					String title = tvTitle.getText().toString();
					orderDialog(Integer.parseInt(tvId.getText().toString()), singer + " - " + title).show();
				}
			});

			layoutMain.addView(lv);
		}

		setContentView(layoutMain);
	}

	private AlertDialog orderDialog(final int i, final String song) {
		// 產生一個Builder物件
		Builder builder = new AlertDialog.Builder(WaitList.this);
		// 設定Dialog的標題
		builder.setTitle(R.string.order_dialog_title);
		// 設定Dialog的內容
		builder.setMessage(song);
		// 待播清單插歌

		builder.setNeutralButton(R.string.string_insert,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String s = Util.DoAction(DoAction.WAIT_INSERT,
								String.valueOf(i));
						if (s.length() < 5) {
							Toast.makeText(WaitList.this,song + " " +
									getText(R.string.toast_insert_success),
									Toast.LENGTH_SHORT).show();
							myVibrator.vibrate(100);
						} else {
							Log.d("insert", s);
							Toast.makeText(WaitList.this,
									R.string.toast_order_fail,
									Toast.LENGTH_SHORT).show();
						}
						getSongList();

					}
				});

		// 刪待播
		builder.setPositiveButton(R.string.string_delete,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						String s = Util.DoAction(DoAction.WAIT_DEL,
								String.valueOf(i));
						if (s.length() < 5) {
							myVibrator.vibrate(100);
						} else {
							Log.d("insert", s);
							Toast.makeText(WaitList.this,
									R.string.toast_operate_fail,
									Toast.LENGTH_SHORT).show();
						}
						getSongList();
					}
				});

		// 利用Builder物件建立AlertDialog
		return builder.create();
	}

	private ListView listView() {
		ListView lv = new ListView(this);
		lv.setFastScrollEnabled(true);
		lv.setVerticalFadingEdgeEnabled(true);
		lv.setFadingEdgeLength(40);
		return lv;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, Menu.FIRST+1, 0, R.string.menu_refresh).setIcon(R.drawable.menu_refresh);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case Menu.FIRST+1:
			this.getSongList();
			break;
		}
		return true;
	}

	// listen "back" action
	private long exitTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), R.string.quit,
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
}
